package com.hknc.btscale.view;

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.hknc.btscale.R;
import com.hknc.btscale.utils.SPUtils;

/**
 * Created by sunguiyong on 2020/12/24
 */
public
class NormalDialogFragment extends DialogFragment {
    private TextView cancel, commit;
    private CommitCallBack mCommitCallBack;
    private EditText baseUrl, wsUrl;

    public CommitCallBack getCommitCallBack() {
        return mCommitCallBack;
    }

    public void setCommitCallBack(CommitCallBack commitCallBack) {
        mCommitCallBack = commitCallBack;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_normal, container, false);
        cancel = view.findViewById(R.id.cancel_tv);
        commit = view.findViewById(R.id.commit_tv);
        baseUrl = view.findViewById(R.id.baseurl_et);
        wsUrl = view.findViewById(R.id.wsurl_et);
        baseUrl.setText(SPUtils.getInstance(getContext()).getSP("base_url"));
        wsUrl.setText(SPUtils.getInstance(getContext()).getSP("ws_url"));
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCommitCallBack.commit(baseUrl.getText().toString(), wsUrl.getText().toString());
            }
        });
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    /*
            因为View在添加后,对话框最外层的ViewGroup并不知道我们导入的View所需要的的宽度。 所以我们需要在onStart生命周期里修改对话框尺寸参数
         */
    @Override
    public void onStart() {
        WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
        params.width = 800;
        params.gravity = Gravity.CENTER;
        getDialog().getWindow().setAttributes((WindowManager.LayoutParams) params);
        super.onStart();
    }

    public interface CommitCallBack {
        void commit(String baseUrl, String wsUrl);
    }
}
